package com.example.algorithm.linear.queue;

import java.util.Iterator;

/**
 * @program: algorithm
 * @description: 队列
 * @packagename: com.example.algorithm.linear.queue
 * @author: Jay
 * @date: 2022/04/27 16:18:04
 **/
public class Queue<T> implements Iterable<T>{
    //记录首结点
    private Node head;
    //记录尾结点
    private Node last;
    //记录元素中个数
    private int N;



    public class Node{
        public T item;
        public Node next;

        public Node(T item, Node next){
            this.item = item;
            this.next = next;
        }
    }

    public Queue(){
        this.head = new Node(null,null);
        this.last = null;
        this.N = 0;
    }

    //判断列表是否是空
    public boolean isEmpty(){
        return N == 0;
    }

    //元素个数
    public int size(){
        return N;
    }

    //向列表中插入元素t
    public void enqueue(T t){
        //当前尾结点last为null
        if (last == null){
            last = new Node(t,null);
            head.next = last;
        }else {
            //当前尾结点lastb不为null
            Node oldLast = last;
            last = new Node(t,null);
            oldLast.next = last;
        }
        N++;
    }

    //拿出
    public T dequeue(){
        if (isEmpty()){
            return null;
        }
        Node oldFirst = head.next;
        head.next = oldFirst.next;
        N--;

        if (isEmpty()){
            last = null;
        }

        return oldFirst.item;
    }

    @Override
    public Iterator iterator() {
        return new QIterator();
    }

    private class QIterator implements Iterator{

        private Node n;

        public QIterator(){
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }

}
